<?php

namespace addons\knowbase;

use app\common\library\Auth;
use app\common\library\Menu;
use app\common\library\Upload;
use app\common\model\knowbase\Project;
use app\common\model\knowbase\ProjectPage;
use think\Addons;
use think\App;
use think\Debug;
use think\Hook;
use think\Lang;
use think\Response;
use think\Route;

/**
 * 插件
 */
class Knowbase extends Addons
{


    protected $menu = [
        [
            'name'    => 'knowbase',
            'title'   => '知识库',
            'icon'    => 'fa fa-list',
            'ismenu'  => 1,
            'weigh'   => 0,
            'remark'  => '',
            'sublist' => [
                [
                    'name'    => 'knowbase/project',
                    'title'   => '知识库项目',
                    'icon'    => 'fa fa-circle-o',
                    'ismenu'  => 1,
                    'weigh'   => 0,
                    'remark'  => '',
                    'sublist' => [
                        ['name' => 'knowbase/project/index', 'title' => '查看'],
                        ['name' => 'knowbase/project/recyclebin', 'title' => '回收站'],
                        ['name' => 'knowbase/project/add', 'title' => '添加'],
                        ['name' => 'knowbase/project/edit', 'title' => '编辑'],
                        ['name' => 'knowbase/project/del', 'title' => '删除'],
                        ['name' => 'knowbase/project/destroy', 'title' => '真实删除'],
                        ['name' => 'knowbase/project/restore', 'title' => '还原'],
                        ['name' => 'knowbase/project/multi', 'title' => '批量更新'],
                        ['name' => 'knowbase/project/export', 'title' => '导出PDF'],
                        ['name' => 'knowbase/project/cloneone', 'title' => '克隆'],
                        ['name' => 'knowbase/project/sitemap', 'title' => '导出网站地图']
                    ]
                ],
                [
                    'name'    => 'knowbase/project_page',
                    'title'   => '知识库文档',
                    'icon'    => 'fa fa-circle-o',
                    'ismenu'  => 0,
                    'weigh'   => 0,
                    'remark'  => '',
                    'sublist' => [
                        ['name' => 'knowbase/project_page/index', 'title' => '查看'],
                        ['name' => 'knowbase/project_page/recyclebin', 'title' => '回收站'],
                        ['name' => 'knowbase/project_page/add', 'title' => '添加'],
                        ['name' => 'knowbase/project_page/edit', 'title' => '编辑'],
                        ['name' => 'knowbase/project_page/del', 'title' => '删除'],
                        ['name' => 'knowbase/project_page/destroy', 'title' => '真实删除'],
                        ['name' => 'knowbase/project_page/restore', 'title' => '还原'],
                        ['name' => 'knowbase/project_page/multi', 'title' => '批量更新'],
                        ['name' => 'knowbase/project_page/cloneone', 'title' => '克隆'],
                        ['name' => 'knowbase/project_page/getList', 'title' => '获取列表'],
                    ]
                ],
                [
                    'name'    => 'knowbase/project_page_history',
                    'title'   => '历史版本',
                    'icon'    => 'fa fa-circle-o',
                    'ismenu'  => 1,
                    'weigh'   => 0,
                    'remark'  => '',
                    'sublist' => [
                        ['name' => 'knowbase/project_page_history/index', 'title' => '查看'],
                        ['name' => 'knowbase/project_page_history/add', 'title' => '添加'],
                        ['name' => 'knowbase/project_page_history/edit', 'title' => '编辑'],
                        ['name' => 'knowbase/project_page_history/del', 'title' => '删除'],
                        ['name' => 'knowbase/project_page_history/multi', 'title' => '批量更新'],
                        ['name' => 'knowbase/project_page_history/remove', 'title' => '删除N天前版本'],
                        ['name' => 'knowbase/project_page_history/reduction', 'title' => '还原老版本'],
                        ['name' => 'knowbase/project_page_history/page_history', 'title' => '查看历史版本']
                    ]
                ],
                [
                    'name'    => 'knowbase/project_page_template',
                    'title'   => '文档模板',
                    'icon'    => 'fa fa-circle-o',
                    'ismenu'  => 1,
                    'weigh'   => 0,
                    'remark'  => '',
                    'sublist' => [
                        ['name' => 'knowbase/project_page_template/index', 'title' => '查看'],
                        ['name' => 'knowbase/project_page_template/add', 'title' => '添加'],
                        ['name' => 'knowbase/project_page_template/edit', 'title' => '编辑'],
                        ['name' => 'knowbase/project_page_template/del', 'title' => '删除'],
                        ['name' => 'knowbase/project_page_template/multi', 'title' => '批量更新'],
                        ['name' => 'knowbase/project_page_template/templates', 'title' => '模板列表']
                    ]
                ],
                [
                    'name'    => 'knowbase/progress',
                    'title'   => '操作日志',
                    'icon'    => 'fa fa-circle-o',
                    'ismenu'  => 1,
                    'weigh'   => 0,
                    'remark'  => '',
                    'sublist' => [
                        ['name' => 'knowbase/progress/index', 'title' => '查看'],
                        ['name' => 'knowbase/progress/add', 'title' => '添加'],
                        ['name' => 'knowbase/progress/edit', 'title' => '编辑'],
                        ['name' => 'knowbase/progress/del', 'title' => '删除'],
                        ['name' => 'knowbase/progress/multi', 'title' => '批量更新'],
                        ['name' => 'knowbase/progress/remove', 'title' => '删除N天前日志']
                    ]
                ],
                [
                    'name'    => 'knowbase/group_new',
                    'title'   => '分组',
                    'icon'    => 'fa fa-circle-o',
                    'ismenu'  => 0,
                    'weigh'   => 0,
                    'remark'  => '',
                    'sublist' => [
                        ['name' => 'knowbase/group_new/index', 'title' => '获取分组']
                    ]
                ],

            ]
        ]
    ];

    /**
     * 插件安装方法
     * @return bool
     */
    public function install()
    {
        Menu::create($this->menu);
        return true;
    }


    /**
     * 插件升级方法
     * @return bool
     */
    public function upgrade()
    {

        Menu::upgrade('knowbase', $this->menu);
        return true;
    }


    /**
     * 插件卸载方法
     * @return bool
     */
    public function uninstall()
    {
        Menu::delete("knowbase");
        return true;
    }


    /**
     * 插件启用方法
     * @return bool
     */
    public function enable()
    {
        Menu::enable("knowbase");
        return true;
    }


    /**
     * 插件禁用方法
     * @return bool
     */
    public function disable()
    {
        Menu::disable("knowbase");
        return true;
    }

    public function appInit()
    {
        define('KNOW_BASE_VERSION', 1);
        define('KNOW_BASE_NONE', 9999999999);
        require_once ADDON_PATH . DS . 'knowbase' . DS . 'common.php';

        $lang = request()->langset();
        $lang = preg_match("/^([a-zA-Z\-_]{2,10})\$/i", $lang) ? $lang : 'zh-cn';
        Lang::load([
            ADDON_PATH . 'knowbase' . DS . 'lang' . DS . $lang . EXT,
        ]);
       
       
       
       
       
       
       
       
        config('url_knowbase_rewrite_page', addon_url('knowbase/index/rewrite_document', [':name' => '{0}', ':id' => '{1}'], true, true));
        config('url_knowbase_page', addon_url('knowbase/index/document', [':id' => '{0}'], true, true));
        config('url_knowbase_project', addon_url('knowbase/index/project', [':id' => '{0}'], true, true));
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
        \think\db\Query::event('after_update', function ($param) {
            if (empty($param['data']) || empty($param['data']['id'])) {
                return;
            }
		
            if (strpos(request()->url(), '/ajax/weigh') === false && strpos(request()->url(), '/restore') === false) {
                return;
            }
            $table = str_replace(config('database.prefix'), '', $param['table']);
            if ($table == 'knowbase_project') {
               
                $row = Project::useGlobalScope(false)->where('id', $param['data']['id'])->find();
                Project::handleAfterUpdate($row);
            } else if ($table == 'knowbase_project_page') {
                $row = ProjectPage::useGlobalScope(false)->where('id', $param['data']['id'])->find();
                ProjectPage::handleAfterUpdate($row);
            }
        });
        config('knowbase_ini', $this->getInfo('knowbase'));
        knowbase_diy_login_url();
        Hook::add('user_sidenav_after', function ($content){
            if (request()->isGet() && request()->module()=='index' && request()->controller()=='User' && knowbase_show_user_navs()) {
                $group_id = Auth::instance()->group_id;
                $projects = array_filter( collection(Project::where('status','1')->field('id,title,user_group_ids')->order('weigh','desc')->select())->toArray(),function ($v) use ($group_id) {
                    if (in_array($group_id,explode(',',$v['user_group_ids']))){
                        return true;
                    }else{
                        return false;
                    }
                });
                if (!$projects){
                    return;
                }
                $html = '<ul class="list-group"><li class="list-group-heading"><i class="fa fa-book"></i> 知识库</li>';
                foreach ($projects as $project){
                    $html .=sprintf('<li class="list-group-item"> <a href="%s" target="_blank">%s</a></li>',addon_url('knowbase/index/project',[':id'=>$project['id']]),$project['title']);
                }
                $html .= '</ul>';
                echo $html;
            }
        });
    }


    public function configInit(&$params)
    {
        $config                   = $this->getConfig();
        $params[$this->addonName] = [
            'classname'        => $config['classname'] ?? '.vditor_editor',
            'editor_theme'     => $config['editor_theme'],
            'content_theme'    => $config['content_theme'],
            'code_theme'       => $config['code_theme'],
            'code_show_number' => $config['code_show_number'],
            'height'           => 500,
            'outline'          => 0,
        ];

        $url                                    = request()->url();
        $params[$this->addonName]['run_script'] = 0;
        if (strpos($url, '/knowbase/') !== false) {
            if (isset($params['upload']) && isset($params['upload']['maxsize']) && isset($config['upload_max_size']) && $config['upload_max_size']) {
                $params['upload']['maxsize'] = $config['upload_max_size'] . 'mb';
            } else {
                $params['upload']['maxsize'] = '10mb';
            }
            $params[$this->addonName]['upload_max_size'] = str_ireplace('mb', '', $params['upload']['maxsize']) * 1024 * 1024;
            if (strpos($url, 'knowbase/project/export') !== false) {
                $params[$this->addonName]['height']  = 0;
                $params[$this->addonName]['outline'] = 1;
            }

            if (strpos($url, '/knowbase/project_page/edit/') !== false) {
                $params[$this->addonName]['show_history'] = \app\admin\library\Auth::instance()->check('knowbase/project_page_history/page_history') ? 1 : 0;
                $params[$this->addonName]['show_link'] =  1 ;
            }

            $params[$this->addonName]['mode'] = $config['editor_mode'] ?? 'wysiwyg';
           
            $params[$this->addonName]['filter_tags'] = $config['filter_tags'] ?? 1;
            $params[$this->addonName]['auto_upload_image_from_text'] = $config['auto_upload_image_from_text'] ?? 0;
        }
        if (strpos($url, 'project_page_history/edit') !== false) {
            $params[$this->addonName]['preview'] = 1;
        }
        if (strpos($url, '/knowbase/') !== false
            && strpos($url, '/project_page') !== false
            &&
            (strpos($url, '/edit') !== false || strpos($url, '/add') !== false)) {
            $params[$this->addonName]['run_script'] = 1;
        }

        if (strpos($url, '/knowbase/project/export') !== false) {
            $params[$this->addonName]['run_script'] = 1;
        }

    }

    public function uploadAfter(\app\common\model\Attachment $attachment){
       
        $config = \Think\Config::get('qiniu', $this->configRange);
        $info = $this->getAddonInfo('qiniu');
        if (strpos(request()->url(), '/knowbase/') !== false && $config && $info && $info['state']) {
            $config['savekey'] = str_replace(
                ['$(year)', '$(mon)', '$(day)', '$(hour)', '$(min)', '$(sec)', '$(etag)', '$(ext)', '$(fname)'],
                ['{year}', '{mon}', '{day}', '$(hour)', '$(min)', '$(sec)', '{filemd5}', '{.suffix}', '{filename}'],
                $config['savekey']
            );
            
            $config['savekey'] = (new Upload())->getSavekey($config['savekey'], $attachment->filename, '$(etag)');
            $policy = array(
                'saveKey' => ltrim($config['savekey'], '/'),
            );
            $auth = new \Qiniu\Auth($config['accessKey'], $config['secretKey']);
            $token = $auth->uploadToken($config['bucket'], null, $config['expire'], $policy);
           
            $uploadMgr = new \Qiniu\Storage\UploadManager();
           
            $saveKey = ltrim($attachment->url, '/');
            try {
               
                $filePath = realpath(ROOT_PATH.'public'.$attachment->url);
                list($ret, $err) = $uploadMgr->putFile($token, $saveKey, $filePath);

                if ($err !== null) {
                    throw new \Exception("七牛云上传失败：".$err);
                }
               
            } catch (\Exception $e) {
               throw $e;
            }
            $hash = @md5_file($attachment->url);
            @unlink($filePath);
            $attachment->storage = 'qiniu';
            $attachment->save();
           
           
           
           
           
            return;
        }
    }
    
    protected function getAddons()
    {
        return array_values(array_filter(scandir(dirname($this->addonPath)), function ($v) {
            return $v !== '.' && $v !== '..' && strpos($v, '.') === false;
        }));
    }
    
    protected function getAddonInfo($name) {
        $infoFile = ADDON_PATH . $name . DS . 'info.ini';
        if (is_file($infoFile)) {
            $info = \Think\Config::parse($infoFile, '', $name, $this->infoRange);
            $info['url'] = addon_url($name);
            return $info; 
        } else {
            return false;
        }
    }
    
}
